package com.zm.tools.util.core.generatecode.commonnew;

import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import static com.zm.tools.util.core.generatecode.common.PackageNameUtil.getPackage;
import static java.lang.System.out;

/**
 * @author zoum
 * @create 2018/10/25 17:14
 */
public class GenerateModelCode {

    private final static Logger LOGGER = LoggerFactory.getLogger(GenerateModelCode.class);
    private final static String MODEL_NAME = "model";

    public static void generate(String baseFilePath, String tableName, String companyName, String appName, List<Map<String, String>> columns) throws IOException{
        String pakage = getPackage(companyName, appName, MODEL_NAME);
        generateModel(baseFilePath, tableName, appName, MODEL_NAME, pakage, columns);
        generateModelConvert(baseFilePath, tableName, appName, MODEL_NAME, pakage);
        GeneratePomCode.generate(baseFilePath, tableName, companyName, appName, 1, MODEL_NAME);
    }

    private static void generateModel(String baseFilePath, String tableName, String appName, String modelName, String pakage, List<Map<String, String>> columns) throws IOException{
        LOGGER.info("generateModel start for " + tableName);
        String model_vo_path = baseFilePath + "\\" + appName + "\\"+ appName + "-" + modelName
                + "\\src\\main\\java\\" + pakage.replace(".", "\\") + "\\vo";
        File model_vo_file  = new File(model_vo_path);
        if (!model_vo_file.exists()){
            boolean result = model_vo_file.mkdirs();
            out.println(result);
        }
        File vo = new File(model_vo_file.getPath(), tableName + "VO.java");
        if (vo.exists()){
            vo.delete();
        }
//        String dtoName = "";
        vo.createNewFile();
        FileWriter fw = new FileWriter(vo);
        StringBuilder sb = new StringBuilder();
        StringBuilder getterAndSetter = new StringBuilder();
        StringBuilder fields = new StringBuilder();
        sb.append("package " + pakage + ".vo;\n\n");
        columns.forEach(columnsMap -> {
            //引用
            if (StringUtils.isNotBlank(columnsMap.get("imports")) && !sb.toString().contains(columnsMap.get("imports"))){
                sb.append("import " + columnsMap.get("imports") +";\n");
            }

            String fieldName = getFieldName(columnsMap.get("fieldName"));
            String fieldType = columnsMap.get("fieldType");

            //属性
            fields.append("    private ").append(fieldType).append(" ").append(fieldName).append(";\n");

            //getterAndSetter
            getterAndSetter.append("    public void set" + StringUtils.capitalize(fieldName) + "("+ fieldType + " " + fieldName +") {\n")
                    .append("       this." + fieldName + " = " + fieldName +";\n")
                    .append("   }\n");
            getterAndSetter.append("    public " + fieldType + " get" + StringUtils.capitalize(fieldName) + "() {\n")
                    .append("       return this." + fieldName +";\n")
                    .append("   }\n\n");

        });
//        sb.append("\n").append("public class " + tableName + "VO extends " + dtoName + " {\n\n"); //这个是继承DTO
        sb.append("\n").append("public class " + tableName + "VO {\n\n");
        sb.append(fields).append("\n").append(getterAndSetter).append("}");
        fw.write(sb.toString());
        fw.flush();
        fw.close();
        LOGGER.info("generateModel start for " + tableName);
    }

    private static void generateModelConvert(String baseFilePath, String tableName, String appName, String modelName, String pakage) throws IOException{
        LOGGER.info("generateModelConvert start for " + tableName);
        String model_vo_path = baseFilePath + "\\" + appName + "\\"+ appName + "-" + modelName +"\\src\\main\\java\\"+ pakage.replace(".", "\\") + "\\convert";
        File model_vo_file  = new File(model_vo_path);
        if (!model_vo_file.exists()){
            model_vo_file.mkdirs();
        }

        String className = tableName+"Convert.java";
        File classFile = new File(model_vo_file.getPath(), className);
        if (classFile.exists()){
            classFile.delete();
        }
        classFile.createNewFile();
        String dtoName = tableName + "DTO";
        String voName = tableName + "VO";
        FileWriter fw = new FileWriter(classFile);
        StringBuilder sb = new StringBuilder();
        sb.append("package "+ pakage +".convert;\n\n")
                .append("import com.rongzhijia.jiedianqian.basic."+ (appName.length()>1 ? appName.split("-")[1] : appName.split("-")[0]) +".model.dto." + tableName.toLowerCase() + "." + dtoName + ";\n")
                .append("import "+ pakage +".vo." + voName + ";\n")
                .append("import org.springframework.beans.BeanUtils;\n")
                .append("import java.util.ArrayList;\n")
                .append("import java.util.List;\n\n")
                .append("public class " + className.split("\\.")[0] + " {\n\n")
                .append("   public static " + dtoName + " toDTO("+ voName +" src" +"){\n")
                .append("       if(src == null){\n")
                .append("           return null;\n")
                .append("       }\n")
                .append("       "+dtoName + " target = new " + dtoName + "();\n")
                .append("       BeanUtils.copyProperties(src, target);\n")
                .append("       return target;\n")
                .append("   }\n")
                .append("   public static " + voName + " toVO("+ dtoName +" src" +"){\n")
                .append("       if(src == null){\n")
                .append("           return null;\n")
                .append("       }\n")
                .append("       "+voName + " target = new " + voName + "();\n")
                .append("       BeanUtils.copyProperties(src, target);\n")
                .append("       return target;\n")
                .append("   }\n")
                .append("   public static List<" + voName + "> toVOS(List<"+ dtoName +"> src" +"){\n")
                .append("       if(src == null || src.isEmpty()){\n")
                .append("           return null;\n")
                .append("       }\n")
                .append("       List<"+voName + "> target = new ArrayList<>();\n")
                .append("       src.forEach(dto -> target.add(toVO(dto)));\n")
                .append("       return target;\n")
                .append("   }\n")
                .append("}");
        fw.write(sb.toString());
        fw.flush();
        fw.close();
        LOGGER.info("generateModelConvert start for " + tableName);
    }

    public static String getFieldName(String src){
        StringBuilder target = new StringBuilder("");
        String[] ary = src.split("_");
        target.append(ary[0]);
        if (ary.length>1){
            for (int i = 1; i < ary.length; i++) {
                target.append(StringUtils.capitalize(ary[i]));
            }
        }
        return target.toString();
    }
}
